#!/bin/ash -efu
#
# mki-cache
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

# retval = 0 - cached
# retval = 1 - not cached

. "${0%/*}"/mki-sh-functions

verbose "has started executing."

[ "$#" -eq 2 ] ||
	fatal "Usage: $PROG <check | build> <target>"

action="$1"; shift

if [ -n "${NO_CACHE:-}" ] && [ "$action" = 'check' ]; then
	verbose "Cache disabled"
	exit 1
fi

cache_type="$1"
case "$cache_type" in
	build-image|copy-packages|copy-subdirs|copy-tree|pack-image) ;;
	prepare-image-workdir|prepare-workdir|run-scripts|run-image-scripts) ;;
	*) fatal "$cache_type: unknown target" ;;
esac
cachefile="$cachedir/mki/$cache_type"

workdir_check_status() {
	return 0
}

workdir_changed="$cachedir/status/workdir-changed"
workdir_change_status() {
	mkdir -p -- "$workdir_changed"
}

. mki-cache-$cache_type

errlock="$cachedir/mki/$cache_type.error"
sha="`{ payload || mkdir -- "$errlock"; } |sha256sum - |cut -d\  -f1`"

if [ -d "$errlock" ]; then
	rm -rf -- "$errlock"
	fatal "Unable to collect payload."
fi

invalid_cache() {
	printf '%s\n' "$sha" > "$cachefile"
	[ "$action" = 'build' ] ||
		workdir_change_status
	exit ${1:-1}
}

[ "$action" != 'build' ] ||
	invalid_cache 0

[ -s "$cachefile" ] ||
	invalid_cache

old_sha="`head -1 "$cachefile"`"
[ "$old_sha" = "$sha" ] ||
	invalid_cache

workdir_check_status ||
	invalid_cache
